<?php
namespace App\Services\Common;

use App\Consts\CacheConst;
use App\Exceptions\ExceptionHelper;
use App\Models\Admin;
use App\Models\AdminMenu;

class AdminService extends BaseService
{
    // 加密
    public static function syncPassWord($pass_word)
    {
        return md5(config('common.admin_secret') . sha1($pass_word));
    }

    // 登录
    public static function login($user_name, $pass_word) {
        $admin = Admin::whereUserName($user_name)->first();
        if (!$admin) {
            throw ExceptionHelper::getInstance(ExceptionHelper::ADMIN_LOGIN_FAILED);
        }
        if ($admin->pass_word != self::syncPassWord($pass_word)) {
            throw ExceptionHelper::getInstance(ExceptionHelper::ADMIN_LOGIN_FAILED);
        }

        if ($admin->isLock()) {
            throw ExceptionHelper::getInstance(ExceptionHelper::USER_IS_LOCK);
        }

        $admin->setLogin();

        session(['admin_info' => ['admin_id' => $admin->id]]);
        session()->save();
    }
    /**
     * 设置权限缓存
     * @param Admin $admin
     * @return false|string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @name:setPermissionCache
     * @author: lisa
     * @datetime: 2021/12/9 13:40
     */
    public static function setPermissionCache($admin) {
        $role = $admin->role;

        // 缓存账号权限
        $menus = AdminMenu::where(function ($query) use($role) {
            if (!$role->is_super) {
                $query->whereIn('id', $role->menu_ids);
            }
        })->get();
        $value = json_encode($menus, JSON_UNESCAPED_UNICODE);
        $key = sprintf(CacheConst::ADMIN_PERMISSIONS, $admin->id);
        CacheService::clearCache(CacheConst::ADMIN_PERMISSIONS,$admin->id);
        \Cache::set($key, $value);
        return $value;
    }
    /**
     * @param Admin $admin
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @name:getPermissionCache
     * @author: lisa
     * @datetime: 2021/12/9 13:33
     */
    public static function getPermissionCache($admin) {
        $key = sprintf(CacheConst::ADMIN_PERMISSIONS, $admin->id);
        $value = \Cache::get($key);
        if (!$value) {
            return self::setPermissionCache($admin);
        }
        return $value;
    }
}
